package server.services;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;

import server.control.Control;
import server.db.EntriesInteraction;
import server.jsons.Daily;
import server.jsons.GsonFactory;
import server.jsons.User;

import com.google.gson.Gson;


@Path("/daily")
public class DailyService {
	private static Logger logger = Logger.getLogger(DailyService.class.getName());
	
	@GET
	@Path("/date")
	@Produces(MediaType.APPLICATION_JSON)
	public String loadDate(@QueryParam("when") String text){
		
		SimpleDateFormat f = new SimpleDateFormat();
		f.applyPattern("yyyy-MM-dd HH:mm:ss");
		
	    Calendar c = new GregorianCalendar();
	    
	    
	    if(text.equals("now")){
	    	return f.format(c.getTime());
	    }else if(text.equals("yesterday")){
	    	c.set(Calendar.HOUR_OF_DAY, 0); //anything 0 - 23
		    c.set(Calendar.MINUTE, 0);
		    c.set(Calendar.SECOND, 0);
	    	c.add(Calendar.DATE, -1);
	    	return f.format(c.getTime());
	    }
	    
	    return null;
	}
	
	 @GET
	 @Produces(MediaType.APPLICATION_JSON)
	 public String loadDaily(@QueryParam("when") String when, String text){
			Control c = Control.getInstance();
			Gson json = GsonFactory.getGson();
			Daily daily = new Daily();
			
			if(when.equals(Control.TODAY)){
				daily.setDate(c.getDateToday());
			}else if(when.equals(Control.YESTERDAY)){
				daily.setDate(c.getDateYesterday());
			}
			
			daily.setMotivation(5);
			daily.setSatisfaction(5);
			daily.setSleeptime("23:00");
			daily.setWaketime("08:00");
			
			return json.toJson(daily);
	 }
	
	@POST
	public String saveDaily(@QueryParam("sessionId") String sessionId, String text){
		Control c = Control.getInstance();
		User u = c.getUser(sessionId);
		Gson json = GsonFactory.getGson();
		Daily daily = json.fromJson(text, Daily.class);
		
		if(u != null){
			logger.info("User " + u.getUserEmail() + " saves his Daily Data.");
			
			
			
			return json.toJson(EntriesInteraction.saveDaily(daily, u));
		}else{
			logger.warn("Security: Unknown Session ID. SessionID: " + sessionId);
			return null;
		}
	}

}
